package ThreadPoolDemo.CyclicBarrierDemo;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zzy on 2018/4/9.
 */
public class CyclicBarrierDemo {

    private CyclicBarrier cyclicBarrier=new CyclicBarrier(4, new Runnable() {
        @Override
        public void run() {
            System.out.println("全部到达");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    private Random random=new Random();

    class TaskDemo implements Runnable{

        private String id;
        TaskDemo(String id){
            this.id=id;
        }
        TaskDemo(){
            this.id=String.valueOf(Thread.currentThread().getId());
        }


        @Override
        public void run() {
            try {

                Thread.sleep(random.nextInt(10000));
                System.out.println("Thread " + id + " will wait");
                cyclicBarrier.await();
                System.out.println("-------Thread " + id + " is over");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        CyclicBarrierDemo cbd = new CyclicBarrierDemo();
        ExecutorService es = Executors.newCachedThreadPool();
        es.submit(cbd.new TaskDemo("a"));
        es.submit(cbd.new TaskDemo("b"));
        es.submit(cbd.new TaskDemo("c"));
        es.submit(cbd.new TaskDemo("d"));
        es.shutdown();
    }
}
